//
//  AddAlarmDeviceViewController.m
//  RONGAO
//
//  Created by wei wang on 2017/7/4.
//  Copyright © 2017年 wei wang. All rights reserved.
//

#import "AddAlarmDeviceViewController.h"
#import <IOTCamera/Camera.h>
#import <IOTCamera/AVIOCTRLDEFs.h>

#import "Alarm433Device.h"

#import "AVIOCTRLDEFuserdefineds.h"

#define MAX_ALIAS_CHAR_LEN      15

#define ALERT_TAG_SUCCESS       100
#define ALERT_TAG_FAIL          200
#define ALERT_TAG_TIMEOUT       300
#define ALERT_TAG_LIMIT         400

#define MAX_CODE_MATCH_TIME     30

#define ALIAS_TEXT_TAG          11

#ifndef SUPPORT_SET_ALIAS
#define SUPPORT_SET_ALIAS
#endif
@interface AddAlarmDeviceViewController ()<MyCameraDelegate>{
    
    BOOL isStopPart;
    BOOL isRecvCodeMatch;
    NSTimer *codeMatchTimer;
    NSInteger codeMatchTimes;
    BOOL isRecvSet;

    NSString *alarmName;

}
@property (strong, nonatomic) IBOutlet UIImageView *errorImage;
@property (strong, nonatomic) IBOutlet UIImageView *bottomBanner;
@property (strong, nonatomic) IBOutlet UIImageView *topBanner;
@property (strong, nonatomic) IBOutlet UILabel *contentLabel;
@property (strong, nonatomic) IBOutlet UIButton *eventBtn;

/** addDevListArr **/
@property(nonatomic,strong) NSMutableArray *addDevListArr;
@end

@implementation AddAlarmDeviceViewController

- (void)timerCodeMatch:(NSTimer *)timer {
    codeMatchTimes += 1;
    NSLog(@"vvvvvvvvvvvvvvvvv timerCodeMatch vvvvvvvvvvvvvvvvv codeMatchTimes:%ld", (long)codeMatchTimes);
    
    if (codeMatchTimes >= MAX_CODE_MATCH_TIME) {
        
        codeMatchTimes = 0;
        [codeMatchTimer setFireDate:[NSDate distantFuture]];

        
    } else {
        
        NSLog(@"isRecvCodeMatch:%d", isRecvCodeMatch);
        if (isRecvCodeMatch) {
            
            
            [self.topBanner stopAnimating];
            [self.bottomBanner stopAnimating];
            codeMatchTimes = 0;
            [codeMatchTimer setFireDate:[NSDate distantFuture]];
        }
    }
}


- (void)viewWillAppear:(BOOL)animated {
    
    self.camera.delegate2 = self;
    [super viewWillAppear:animated];
    
    isRecvCodeMatch = NO;
    isStopPart = NO;
    
    codeMatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerCodeMatch:) userInfo:nil repeats:YES];
    codeMatchTimes = 0;
    [codeMatchTimer setFireDate:[NSDate distantFuture]];
    [codeMatchTimer setFireDate:[NSDate distantPast]];
    codeMatchTimes = 0;
    [self setbannerImage];

    [self staryPairReq];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setNavigationStyle];
    alarmName = nil;

}

- (void)viewDidUnload {
    
    self.camera = nil;
    [super viewDidUnload];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    codeMatchTimes = 0;
    [codeMatchTimer setFireDate:[NSDate distantFuture]];
}

- (void)setbannerImage{
    
    NSArray *topimage = @[@"match1",@"match2",@"match3"];
    NSArray *bottomimage = @[@"match4",@"match5",@"match6"];
    
    NSMutableArray *topArray = [NSMutableArray array];
    
    for (int i = 0; i < topimage.count; i++) {
        
        UIImage *image = [UIImage imageNamed:bottomimage[i]];
        [topArray addObject:image];
    }
    
    NSMutableArray *bottomArray = [NSMutableArray array];
    
    for (int i = 0; i < bottomimage.count; i++) {
        
        UIImage *image = [UIImage imageNamed:topimage[i]];
        [bottomArray addObject:image];
    }
    
    self.topBanner.animationImages = topArray;
    self.topBanner.animationRepeatCount = 0;
    self.topBanner.animationDuration = 0.9f;
    
    self.bottomBanner.animationImages = bottomArray;
    self.bottomBanner.animationRepeatCount = 0;
    self.bottomBanner.animationDuration = 0.9f;
}

#pragma mark - 发送对码指令

- (void)staryPairReq{
    
    self.errorImage.hidden = YES;
    self.topBanner.hidden = NO;
    self.bottomBanner.hidden = NO;
    [self.eventBtn setTitle:@"退出对码" forState:UIControlStateNormal];
    [self.eventBtn setBackgroundImage:[UIImage imageNamed:@"login_button_nor"] forState:UIControlStateNormal];
    SmsgAVIoctrlStartPairReq *s = malloc(sizeof(SmsgAVIoctrlStartPairReq));
    memset(s, 0, sizeof(SmsgAVIoctrlStartPairReq));
    
    s->pair_device_type_ = self.typeInt;
    
    [self.camera sendIOCtrlToChannel:0
                           Type:IOTYPE_USER_IPCAM_433_START_PAIR_REQ
                           Data:(char *)s
                       DataSize:sizeof(SmsgAVIoctrlStartPairReq)];
    free(s);
    self.contentLabel.text = @"正在对码请稍等......";
    

    [self.topBanner startAnimating];

    [self.bottomBanner startAnimating];
}

- (IBAction)pariEvent:(UIButton *)sender {
    
    if ([sender.titleLabel.text isEqualToString:@"退出对码"]) {
        //退出对码
        // set info
        SmsgAVIoctrlStopPairReq *s = malloc(sizeof(SmsgAVIoctrlStopPairReq));
        memset(s, 0, sizeof(SmsgAVIoctrlStopPairReq));
        
        [self.camera sendIOCtrlToChannel:0
                                    Type:IOTYPE_USER_IPCAM_433_STOP_PAIR_REQ
                                    Data:(char *)s
                                DataSize:sizeof(SmsgAVIoctrlStopPairReq)];
        free(s);
        
        
        
        [self.navigationController popViewControllerAnimated:YES];

    }else if ([sender.titleLabel.text isEqualToString:@"重试"] || [sender.titleLabel.text isEqualToString:@"继续对码"]){
        
        [self staryPairReq];
        
    }
    
    
    
}


#pragma mark - MyCameraDelegate Methods
- (void)camera:(MyCamera *)camera_ _didReceiveIOCtrlWithType:(NSInteger)type Data:(const char *)data DataSize:(NSInteger)size {
    NSLog(@"AADVC _didReceiveIOCtrlWithType type:%lx", (long)type);
    
    
    if (camera_ == self.camera) {
        
        if (type == IOTYPE_USER_IPCAM_433_START_PAIR_RESP) {
            
            isRecvCodeMatch = YES;
            
            SmsgAVIoctrlStartPairResp *s = (SmsgAVIoctrlStartPairResp*)data;
            
            if (0 == s->result_) {
                
                Alarm433Device *dev = [[Alarm433Device alloc] init];
                dev.device_type = s->device_info_.device_type_;
                dev.device_vender = s->device_info_.device_vender_;
                dev.key = [NSString stringWithFormat:@"%s", s->device_info_.key_];
                //dev.alias = [];
                
                NSLog(@"IOTYPE_USER_IPCAM_433_START_PAIR_RESP dev.device_type:%ld, dev.device_vender:%ld, dev.key:%@", (long)dev.device_type, (long)dev.device_vender, dev.key);
                
                [self.addDevListArr addObject:dev];
                
                NSString *str = [NSString stringWithFormat:@"%@; %@", NSLocalizedString(@"Code Matching Success",nil), NSLocalizedString(@"Enter an alias for device",nil)];
                NSString *keystr = [NSString stringWithFormat:@"%s", s->device_info_.key_];
                NSLog(@"key keystr:%@", keystr);
                
                NSLog(@"self.defaultAlias:%@", self.defaultAlias);

                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"对码成功" message:@"请输入别名" preferredStyle:UIAlertControllerStyleAlert];
                
                [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField){
                    textField.placeholder = @"请输入别名";
                }];
                __weak typeof(alertController) alere = alertController;
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
                UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    
                      if (![NSString isContainsTwoEmoji:alere.textFields.firstObject.text]&&[alere.textFields.firstObject.text length]<=8){

                          alarmName = [NSString stringWithFormat:@"%@",alere.textFields.firstObject.text];
                          
                          Alarm433Device *dev = (Alarm433Device *)[self.addDevListArr objectAtIndex:0];
                          NSString *key = dev.key;
                          NSLog(@"key:%@", key);
                          
                          NSString *alias = alere.textFields.firstObject.text;
                          NSLog(@"alias:%@", alias);
                          
                          
                          SmsgAVIoctrlSet433DevicesAliasReq *s = malloc(sizeof(SmsgAVIoctrlSet433DevicesAliasReq));
                          memset(s, 0, sizeof(SmsgAVIoctrlSet433DevicesAliasReq));
                          
                          memcpy(s->device_id, [key UTF8String], 16);
                          memcpy(s->device_alias , [alias UTF8String], 16);
                          
                          // init
                          s->is_alarmed = 1;
                          s->ptz_preset = 0;
                          s->device_closed = 0;
                          
                          [self.camera sendIOCtrlToChannel:0
                                                 Type:IOTYPE_USER_IPCAM_433_SET_ALIAS_REQ
                                                 Data:(char *)s
                                             DataSize:sizeof(SmsgAVIoctrlSet433DevicesAliasReq)];
                          free(s);
                          
                          isRecvSet = NO;

                          [SVProgressHUD showWithStatus:@"保存中..."];
                          dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                              
                              SmsgAVIoctrlStopPairReq *s = malloc(sizeof(SmsgAVIoctrlStopPairReq));
                              memset(s, 0, sizeof(SmsgAVIoctrlStopPairReq));
                              
                              [self.camera sendIOCtrlToChannel:0
                                                          Type:IOTYPE_USER_IPCAM_433_STOP_PAIR_REQ
                                                          Data:(char *)s
                                                      DataSize:sizeof(SmsgAVIoctrlStopPairReq)];
                              free(s);
                              
                              UIViewController *controller = self.navigationController.viewControllers[1];
                              [self.navigationController popToViewController:controller animated:YES];
                              
                          });
                          
        
                          
                      }
                    
                }];
                
                [alertController addAction:cancelAction];
                [alertController addAction:okAction];
                [self presentViewController:alertController animated:YES completion:nil];

                
                codeMatchTimes = 0;
                [codeMatchTimer setFireDate:[NSDate distantFuture]];

                [self.topBanner stopAnimating];
                [self.bottomBanner stopAnimating];
                [self.contentLabel setText:@"对码成功"];
                [self.eventBtn setTitle:@"继续对码" forState:UIControlStateNormal];
                [self.eventBtn setBackgroundImage:[UIImage imageNamed:@"login_button_nor"] forState:UIControlStateNormal];
                
            } else {

                
                [self.topBanner stopAnimating];
                [self.bottomBanner stopAnimating];
                self.topBanner.hidden = YES;
                self.bottomBanner.hidden = YES;
                self.errorImage.hidden = NO;
                [self.contentLabel setText:@"对码失败"];
                [self.eventBtn setBackgroundImage:[UIImage imageNamed:@"button_photo_sel"] forState:UIControlStateNormal];
                [self.eventBtn setTitle:@"重试" forState:UIControlStateNormal];
                
                
            }
            
        } else if (type == IOTYPE_USER_IPCAM_433_STOP_PAIR_RESP) {
            
            isStopPart = YES;
            
        } else if (type == IOTYPE_USER_IPCAM_433_SET_ALIAS_RESP) {
            SmsgAVIoctrlSet433DevicesAliasResp *s = (SmsgAVIoctrlSet433DevicesAliasResp*)data;
            NSLog(@"IOTYPE_USER_IPCAM_433_SET_ALIAS_RESP s->result_:%d", s->result_);
            if (0 == s->result_) {
                isRecvSet = YES;
                
                Alarm433Device *d0 = (Alarm433Device *)[self.addDevListArr objectAtIndex:0];
                NSString *alias = alarmName;
                NSLog(@"alias:%@", alias);
                d0.alias = [[NSString alloc] initWithString:alias];
                [self.addDevListArr removeAllObjects];
                [self.addDevListArr addObject:d0];
                
            }
        }
    }
}

- (NSMutableArray *)addDevListArr{
    
    if (!_addDevListArr) {
        
        _addDevListArr = [NSMutableArray array];
        
    }
    return _addDevListArr;
}

- (void)setNavigationStyle{
    
    [self setLeftButtonImage:[UIImage imageNamed:@"icon_back_nor"]];
    [self setNavigationTitle:[NSString stringWithFormat:@"%@新增",self.titleName] titleColor:[UIColor colorWithRed:210/255.0 green:177/255.0 blue:104/255.0 alpha:1]];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
